/*
 * @Author: lanbin
 * @Date: 2020-11-12 09:46:22
 * @Last Modified by: lanbin
 * @Last Modified time: 2020-12-01 14:19:38
 */
let OSS = require('ali-oss');

let installed = false;

const getFileNameUUID = () => {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${+new Date()}_${rx()}${rx()}`;
};

export default (Vue, options) => {
  if (!installed) {
    installed = true;

    // 上传方法
    const { method } = options;
    const isDev = process.env.NODE_ENV === 'development';

    Vue.prototype.$UploadCore = ({
      isPublic = false,
      useFileName = false,
      folder = 'other',
      file = {},
    }) => {
      // 判断素材是否走公有路径
      const R = isPublic ? method.public : method.internal;
      console.log(file);
      return R()
        .then((res) => {
          const client = new OSS({
            region: 'oss-cn-shanghai',
            secure: true, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
            accessKeyId: res.accessKeyId,
            accessKeySecret: res.accessKeySecret,
            // 开发环境是一个bucket, 生产环境是要区分两个bucket
            bucket: isDev ? 'mutong-ketang-img' : isPublic ? 'ketang-pub' : 'ketang-internal',
            stsToken: res.securityToken,
            timeout:600000, // 请求时间600000ms
            endpoint : isDev ? '' : 'movtile.com',
          });

          const fileType = file.name.match(/(\.\w+)?$/);
          // 文件路径
          let storeAs = [
            folder,
            useFileName ? file.name : getFileNameUUID() + (fileType ? fileType[0] : ''),
          ].join('/');
          // 如果folder有值 stareAs生成 "xxx/yyy" 所以需要前面再加一个 "/"
          // if (folder) {
          //   storeAs = '/' + storeAs;
          // }

          return client.put(storeAs, file);
        })
        .catch((err) => {
          console.log(err);
        });
    };
  }
};
